import axios from 'axios';
// import qs from 'qs'

import { ElMessage, ElLoading } from "element-plus";

let loading = null

let baseURL = ''
if (process.env.NODE_ENV == 'development') {
    baseURL = 'http://localhost:8080/'
} else {
    // baseURL = 'http://move.eartag.huatengfood.com:8820/'
    // baseURL = ''
}

const service = axios.create({
    timeout: 10000,                                   //超时时间
    baseURL: baseURL,             // 我们在请求接口的时候就不用写前面 会自动我们补全
    // transformRequest: data => qs.stringify(data)    //post请求参数处理,防止post请求跨域
})


// http request 拦截器
service.interceptors.request.use(config => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0)',
    })

// get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            let part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof(value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        let subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}, err => {
    return err
})
// http response 拦截器
service.interceptors.response.use(response => {
    loading.close()

    const res = response.data
    //判断返回数据是否存在状态code和错误提示信息..
    // if (!res.code || !res.msg) {
    //     return showMessage('响应数据格式错误', "error")
    // }
    //判断状态code是否为指定数值(200)..
    if (res.code != 200) {
        return showMessage(res)
    }
    //接收返回数据..
    return res
}, err => {
    console.log("请求错误")
    // return err

    loading.close()
    return showMessage(err)
})


//封装错误提示信息..
function showMessage(err) {
    ElMessage.error(err.message)
    return Promise.reject(err)
}

export default service;

export let get = (url, params) => {
    return new Promise((resolve, reject) => {
        service.get(url, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    })
}
